package cn.com.yang.nio;


import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/**
 * @Author 杨亿金
 * @Date 2021/12/22 19:58
 * @CopyRight
 * @Version
 */
public class FileChannelDemo {
    /**
     * 通过FileChannel读取数据
     * @throws IOException
     */
    @Test
    public void readFileByChannel() throws IOException {
        FileInputStream inputStream = new FileInputStream("E://test.txt");
        //从FileInputStream获取channel
        FileChannel fc = inputStream.getChannel();
        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将数据从channel写入Buffer
        fc.read(buffer);
        buffer.flip();
        while (buffer.remaining()>0){
            byte b = buffer.get();
            System.out.println((char)b);
        }
        inputStream.close();
    }

    /**
     * 通过FileChannel写入数据
     */
    @Test
    public void writeFileChannel() throws IOException {
        /**
         * 查表ASCII
         * 83大写的S
         * 111 小写0
         * 109 小写m
         * 101 小写e
         *  32 空格
         *  98 小写b
         *  121 小写y
         *  116 小写t
         *  101 小写e
         *  115 小写s
         *  46  英文句号.
         */
        final byte message[]={83,111,109,101,32,98,121,116,101,115,46};
        FileOutputStream outputStream = new FileOutputStream("E://testOut.txt");
        FileChannel fc = outputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        for (int i = 0; i <message.length ; i++) {
            buffer.put(message[i]);
        }
        buffer.flip();
        fc.write(buffer);
        outputStream.close();
    }
}
